package com.ews.onlineexchange.service.temp;

import java.util.ArrayList;
import java.util.List;

import javax.enterprise.inject.Model;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;

import org.apache.log4j.Logger;
import org.hibernate.CacheMode;
import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;

import com.ews.onlineexchange.controller.ServiceSupplierManageList;
import com.ews.onlineexchange.model.Business;
import com.ews.onlineexchange.model.MainBusiness;
import com.ews.onlineexchange.model.ServiceSupplier;

@Model
public class BusinessToMainBusinessConverter {
	
	private static Logger logger = Logger.getLogger( BusinessToMainBusinessConverter.class );
	
	@Inject
	EntityManager entityManager;
	
	private static final String QUERY_ALL_SUPPLIERS_EQL = ""
			+ "		SELECT			ss"
			+ "		FROM			ServiceSupplier ss 	left join fetch ss.businesses ";	
	@Inject
	ServiceSupplierManageList serviceSupplierManageList;
	
	@Transactional
	public String convert() {
		
		Session session = entityManager.unwrap( Session.class );	

		ScrollableResults sr = session
	        .createQuery( QUERY_ALL_SUPPLIERS_EQL )
	        .setCacheMode( CacheMode.IGNORE )
	        .scroll( ScrollMode.FORWARD_ONLY );
		long count = 0L;
		while (sr.next()) {
			ServiceSupplier _ss = (ServiceSupplier) sr.get( 0 );
			
			for ( Business _b : _ss.getBusinesses() ) {
				MainBusiness mb = new MainBusiness();
				mb.setAgentService( _b.getAgentService() );
				mb.setAgentServiceDetail( _b.getAgentServiceDetail() );
				mb.setCommitOfPrice( _b.getCommitOfPrice() );
				mb.setCommitOfQuality( _b.getCommitOfQuality() );
				mb.setCommitOfTime( _b.getCommitOfTime() );			
				_ss.addMainBusiness( mb );
			}
			session.update( _ss );
			count++;
			if (count % 100 == 0) {
				session.flush();
			}
		}
		
		session.flush();
		sr.close();
		logger.info( "convert complete" );
		
		return "ok";
		
	}
	
}
